const router = require('koa-router')()

const classService = require('../../services/class');

const msgModule = require('../../common/msg');
const Result = require('../../common/Result');

router.prefix('/class')

router.post('/list', async function (ctx, next) {
  let param = ctx.request.body;
  try {
    const classData = await classService.list(param);
    ctx.body = Result.success(classData, msgModule.querySuccess)
  } catch (error) {
    ctx.body = Result.error(error, msgModule.queryError)
  }
});

router.get('/byId', async (ctx, next) => {
  let param = ctx.request.query;
  try {
    const classData = await classService.byId(param._id);

    if (classData._id) {
      ctx.body = Result.success(classData, msgModule.querySuccess);
    } else {
      ctx.body = Result.fail({}, msgModule.queryError);
    }
  } catch (error) {
    console.log(error);
    ctx.body = Result.error(error, msgModule.queryError);
  }
});

router.post('/add', async function (ctx, next) {
  let param = ctx.request.body;
  try {
    const classData = await classService.add(param);
    if (classData.id) {
      ctx.body = Result.success(classData, msgModule.addSuccess);
    } else {
      ctx.body = Result.fail({}, msgModule.classTimeError);
    }
  } catch (error) {
    ctx.body = Result.error(error, msgModule.addError);
  }
});

router.post('/edit', async function (ctx, next) {
  let param = ctx.request.body;
  try {
    const classData = await classService.edit(param);
    if (classData) {
      ctx.body = Result.success(classData, msgModule.editSuccess);
    } else {
      ctx.body = Result.fail({}, msgModule.classTimeError);
    }
  } catch (error) {
    ctx.body = Result.error(error, msgModule.editError);
  }
});

router.post('/reservation', async function (ctx, next) {
  let param = ctx.request.body;
  try {
    const classData = await classService.reservation(param);
    if (classData.status) {
      ctx.body = Result.success(classData, msgModule.reservationSuccess);
    } else {
      ctx.body = Result.fail({}, msgModule.reservationError);
    }
  } catch (error) {
    ctx.body = Result.error(error, msgModule.reservationError);
  }
});

router.post('/cancel', async function (ctx, next) {
  let param = ctx.request.body;
  try {
    const classData = await classService.cancel(param);
    if (classData.status) {
      ctx.body = Result.success(classData, msgModule.cancelSuccess);
    } else {
      ctx.body = Result.fail({}, msgModule.cancelError);
    }
  } catch (error) {
    ctx.body = Result.error(error, msgModule.cancelError);
  }
});

module.exports = router